package com.download.web.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blade.exception.ValidatorException;
import com.download.web.entity.SysThirdUser;
import com.download.web.entity.SysUser;
import com.download.web.entity.model.Result;
import com.download.web.pay.MakeMoneyService;
import com.download.web.pay.enums.PlatFormEnum;
import com.download.web.service.ISysThirdUserService;
import com.download.web.service.ISysUserService;
import com.sun.mail.imap.protocol.ID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cmy
 * @since 2019-02-20
 */
@Slf4j
@Controller
@RequestMapping("/download/sys-user")
public class SysUserController  {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private ISysThirdUserService thirdUserService;

    @ResponseBody
    @RequestMapping("/login")
    public Result<String> login(String email, String pwd,  HttpServletRequest request){
        SysUser user=userService.login(email,pwd);
        String  msg="";
        Integer code=0;
        if(user==null){
            msg="帐号或密码错误";
            code=400;
        }else{
            if(user.getState()!=6){
                msg="帐号状态异常";
                code=400;
            }else {
                request.getSession().setAttribute("user",user);
//                model.addAttribute("user",user);
//                model.addAttribute("msg",msg);
//                return "redirect:/";
                msg="登陆成功";
            }
        }
        Result result=new Result(null,msg,code);
//        model.addAttribute("msg",msg);
//        return "/web/login";
        return result;
    }

    @ResponseBody
    @RequestMapping("/register")
    public  Result register(@RequestBody @Valid SysUser user, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return Result.error(bindingResult.getFieldErrors().get(0).getDefaultMessage());
        }
        user.setIsVip("0");
        user.setState(6);
        int pan=userService.count(new QueryWrapper<SysUser>().eq("email",user.getEmail()));
        String msg="注册成功";
        if(pan>0){
            msg="此邮箱已存在";
            return Result.error(msg);
//            model.addAttribute("msg",msg);
//            return "/web/register";
        }
        int count=userService.register(user);
        if(count<=0) {
            msg="系统异常";
            return Result.error(msg);
        }
        return Result.ok(null,msg);
    }
    @RequestMapping("/thirdRegister")
    public ModelAndView thirdRegister(SysUser user, SysThirdUser thirdUser){
        ModelAndView mv=new ModelAndView();
        user.setIsVip("0");
        user.setState(6);
        int pan=userService.count(new QueryWrapper<SysUser>().eq("email",user.getEmail()));
        if(pan>0){
            mv.addObject("msg","此邮箱已存在");
            mv.addObject("thirdUser",thirdUser);
            mv.setViewName("/web/thirdregister");
        }
        int count=userService.register(user);
        if(count<=0) {
            mv.addObject("msg","系统异常");
            mv.addObject("thirdUser",thirdUser);
            mv.setViewName("/web/thirdregister");
        }else {
            thirdUser.setUserId(user.getId());
            thirdUserService.save(thirdUser);
            mv.setViewName("/index");
            mv.addObject("user", user);
            mv.addObject("thirdUser",thirdUser);
        }
        return mv;
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "web/login";
    }

    @RequestMapping("/toRegister")
    public String toRegister(){
        return "web/register";
    }

    @RequestMapping("/sendMail")
    @ResponseBody
    public Result sendMail(String email){
        SysUser user=userService.getOne(new QueryWrapper<SysUser>().eq("email",email));
        if(user==null){
            return Result.error("没有此用户！请先注册");
        }
        sendEmail(email,user);
        return Result.ok(null,"已发送至邮箱！");
    }

    public  void sendEmail(String email,SysUser user) {
        MimeMessage message = null;
        try {

            message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("1174022880@qq.com");
            helper.setTo(email);
            helper.setSubject("找回密码");
            StringBuffer sb = new StringBuffer();
            sb.append("<h1>您的密码是：</h1>")
                    .append("<p style='color:#F00'>"+user.getPwd()+"</p>")
                    .append("<p style='text-align:right'>请记录</p>");
            helper.setText(sb.toString(), true);
            //FileSystemResource fileSystemResource=new FileSystemResource(new File("D:\76678.pdf"));
            //helper.addAttachment("电子发票",fileSystemResource);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/userCenter")
    public ModelAndView userCenter(Integer userId){

        ModelAndView mv=new ModelAndView("web/mine");
        return mv;
    }

    @ResponseBody
    @RequestMapping("/updateUserName")
    public String updateUserName(String userName,Integer userId,HttpServletRequest request){
        userService.updateUserName(userName, userId);
        SysUser user=userService.getById(userId);
        request.getSession().setAttribute("user",user);
        return null;
    }
    @ResponseBody
    @RequestMapping("/updateUserImg")
    public String updateUserImg(String userImg,Integer userId,HttpServletRequest request){
        userService.updateUserImg(userImg, userId);
        SysUser user=userService.getById(userId);
        request.getSession().setAttribute("user",user);
        return null;
    }

    @ResponseBody
    @RequestMapping("/updatePwd")
    public String updatePwd(String pwd,Integer userId){
        userService.updatePwd(pwd, userId);
        return "修改成功";
    }


    @ResponseBody
    @RequestMapping("/logout")
    public void logout(HttpServletRequest request){
        request.getSession().invalidate();
    }

}
